package com.th.example.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.jupiter.api.Test;

import java.nio.charset.Charset;

public class CompositeBufferTest {
    static Charset utf8 = Charset.forName("UTF-8");

    @Test
    public  void byteBufComposite(){
        CompositeByteBuf  cbuf = ByteBufAllocator.DEFAULT.compositeBuffer();;

        //消息头
        ByteBuf headerBuf = Unpooled.copiedBuffer("java RPC 框架：",utf8);
        //消息体
        ByteBuf bodyBuf = Unpooled.copiedBuffer("高性能netty",utf8);

        ByteBuf allByte = Unpooled.wrappedBuffer(headerBuf,bodyBuf);
        cbuf.addComponents(headerBuf,bodyBuf);
        sendMsg(cbuf);



    }

    private void sendMsg(CompositeByteBuf cbuf) {
        //处理整个消息
        for (ByteBuf b : cbuf){
            int length = b.readableBytes();
            byte[]  array = new byte[length];
            //将CompositeByteBuf 中的数据，统一复制到数组中
            b.getBytes(b.readerIndex(),array);

            //处理一下数组中的数据
            System.out.println(new String(array,utf8));
        }
        System.out.println("cbuf = " + cbuf);
    }
}
